package com.moyv.schoolbbs.ui.activity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.tabs.TabLayout;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.moyv.schoolbbs.R;
import com.moyv.schoolbbs.config.AccountConstant;
import com.moyv.schoolbbs.ui.adapter.DataGenerator;
import com.moyv.schoolbbs.ui.fragment.HomeFragment;
import com.moyv.schoolbbs.ui.fragment.MeFragment;
import com.moyv.schoolbbs.ui.fragment.MessageFragment;
import com.moyv.schoolbbs.ui.service.ChatService;
import com.moyv.schoolbbs.util.GlideCacheUtil;

import java.util.List;

import static android.content.ContentValues.TAG;
import static com.moyv.schoolbbs.config.AccountConstant.ACCOUNT;
import static com.moyv.schoolbbs.config.AccountConstant.LOGIN;
import static com.moyv.schoolbbs.service.PictureService.uploadHead;
import static com.moyv.schoolbbs.ui.adapter.DataGenerator.mTabTitle;
import static com.moyv.schoolbbs.util.ToastUtils.init;
import static com.moyv.schoolbbs.util.ToastUtils.show;
import static com.moyv.schoolbbs.util.UIHelper.closeDialog;
import static com.moyv.schoolbbs.util.UIHelper.showDialogForLoading;

/**
 * @author moyv
 */
public class BottomTabLayoutActivity extends AppCompatActivity {
    private TabLayout mTabLayout;
    private Fragment[] mFragmensts;
    private Fragment currentFragment;
    private Context context;

//    private ServiceConnection conn;
    private static ChatService chatService;


    public static ChatService getChatService() {
        return chatService;
    }

    public void setChatService(ChatService chatService) {
        this.chatService = chatService;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bottom_tab_layout_ac);
        mFragmensts = DataGenerator.getFragments("TabLayout Tab");
        context = this;
        new AccountConstant(context);
        init(context);
        initView();

        initFragment();
    }

    //    初始化布局
    private void initView() {
        mTabLayout = findViewById(R.id.bottom_tab_layout);
        currentFragment = new HomeFragment();
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                onTabItemSelected(tab.getPosition());

                //改变Tab 状态
                for (int i = 0; i < mTabLayout.getTabCount(); i++) {
                    if (i == tab.getPosition()) {
                        mTabLayout.getTabAt(i).setIcon(getResources().getDrawable(DataGenerator.mTabResPressed[i]));
                    } else {
                        mTabLayout.getTabAt(i).setIcon(getResources().getDrawable(DataGenerator.mTabRes[i]));
                    }
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

//        图片和标题设置
        if (LOGIN) {
            mTabTitle[2] = "我的";
        }
        mTabLayout.addTab(mTabLayout.newTab().setIcon(getResources().getDrawable(R.drawable.tab_home_selector2)).setText(mTabTitle[0]));
        mTabLayout.addTab(mTabLayout.newTab().setIcon(getResources().getDrawable(R.drawable.tab_message_selector)).setText(mTabTitle[1]));
        mTabLayout.addTab(mTabLayout.newTab().setIcon(getResources().getDrawable(R.drawable.tab_me_selector)).setText(mTabTitle[2]));

    }

    /**
     * 初始化fragment
     */
    private void initFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.home_container, mFragmensts[1], mFragmensts[1].getClass().getName()).hide(mFragmensts[1]);
        transaction.add(R.id.home_container, mFragmensts[2], mFragmensts[2].getClass().getName()).hide(mFragmensts[2]);
        transaction.commit();
    }

    /**
     * 页面切换
     */
    private void onTabItemSelected(int position) {
        Fragment fragment = mFragmensts[position];
        showFragment(fragment);
    }

    /**
     * 使用show() hide()切换页面
     * 显示fragment
     */
    private void showFragment(Fragment fg) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //如果之前没有添加过
        if (!fg.isAdded()) {
            transaction
                    .hide(currentFragment)
                    .add(R.id.home_container, fg, fg.getClass().getName());
            //第三个参数为当前的fragment绑定一个tag，tag为当前绑定fragment的类名
        } else {
            transaction
                    .hide(currentFragment)
                    .show(fg);
        }
        currentFragment = fg;
        transaction.commit();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e(TAG, "onActivityResult: 回调成功");
        switch (requestCode) {
            //相册
            case PictureConfig.CHOOSE_REQUEST:
                if (resultCode == RESULT_OK) {
//                    系统相册调用
//                    Uri sourceUri = data.getData();
//                    uCropUtils.startUCrop(sourceUri);
//                    图片选择器调用



                    List<LocalMedia> imageUrl = PictureSelector.obtainMultipleResult(data);
                    upload(imageUrl);
                } else {
                    show("头像选择失败");
                }
                break;
            //照相
            case PictureConfig.REQUEST_CAMERA:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
//                        uCropUtils.startUCrop(imageUri);
                        // 结果回调
                        List<LocalMedia> result = PictureSelector.obtainMultipleResult(data);
                        upload(result);
                    } else {
                        show("拍照失败");
                    }
                }
                break;
            default:
        }
    }

    public void upload(List<LocalMedia> result) {
        List<LocalMedia> imageUrl = result;
        Handler handler1 = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case 200:
                        show("头像上传成功");
//                                    刷新用户信息
//                    清除图片缓存
                        GlideCacheUtil glideCacheUtil;
                        glideCacheUtil = GlideCacheUtil.getInstance();
                        glideCacheUtil.clearImageAllCache(context);


                        mFragmensts[2].onResume();
                        closeDialog(context);

                        break;
                    case 301:
                        show("上传失败");
                        break;
                    case 404:
                        show("服务器出错");
                        break;
                    default:
                }
                return false;
            }
        });
        showDialogForLoading(context, "头像上传中");
        uploadHead(imageUrl.get(0).getCompressPath(), ACCOUNT, handler1);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        标题更新
        if (LOGIN) {
            mTabTitle[2] = "我的";
        } else {
            mTabTitle[2] = "未登录";
        }
    }
}
